import test from "../helper/test";
const CDN_URL = import.meta.env.LM_CDN_URL
const STATIC_URL = import.meta.env.LM_STATIC_URL
/** 添加cdn域名前缀 */
export const _cdn = (url = '', cdnurl = '') => {
	if (!url) return '';
	if (url.indexOf('http') === 0) {
		return url;
	}
	if (cdnurl === '') {
		cdnurl = CDN_URL;
	}
	return cdnurl + url;
};
/**  静态资源地址 */
export const _static = (url = '', staticurl = '') => {

	if (staticurl === '') {
		staticurl = STATIC_URL;
	}
	if (staticurl !== 'local') {
		url = _cdn(url, staticurl);
	}
	return url;
};
/** css背景图片地址 */
export const _css = (url = '', staticurl = '') => {
	if (staticurl === '') {
		staticurl = STATIC_URL;
	}
	if (staticurl !== 'local') {
		url = _cdn(url, staticurl);
	}
	// #ifdef APP-PLUS
	if (staticurl === 'local') {
		url = plus.io.convertLocalFileSystemURL(url);
	}
	// #endif
	// #ifdef H5
	if (staticurl === 'local') {
		url = `/h5${url}`;
	}
	// #endif
	return `url(${url})`;
}
/** 从完整URL中提取路径部分（去除协议和域名） */
export const _urlPath = (fullUrl) => {
	if (!test.url(fullUrl)) return fullUrl

	// 统一使用字符串处理方式，适用于所有环境 
	const urlObj = parseUrl(fullUrl);
	return urlObj.pathname;
}

/** 解析URL的辅助函数 */
function parseUrl(fullUrl) {
	// 提取协议部分 
	const protocolMatch = fullUrl.match(/^([a-z]+:)?\/\//i);
	const protocol = protocolMatch ? protocolMatch[0] : '';

	// 移除协议部分
	const rest = fullUrl.slice(protocol.length);

	// 分割域名和路径 
	const [domain, ...pathParts] = rest.split('/');
	const pathname = '/' + pathParts.join('/');

	return {
		protocol,
		hostname: domain,
		pathname
	};
}

// 默认导出
export default {
	_cdn,
	_static,
	_css,
	_urlPath
}